package com.example.pdf;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.utils.PdfMerger;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author mrcode
 * @date 2022/1/21 20:28
 */
public class Pdf7Demo {
    public static void main(String[] args) throws IOException {
        final List<String> list = new ArrayList<>();
        list.add("C:\\Users\\zhbcm\\Desktop\\readme1.pdf");
        list.add("C:\\Users\\zhbcm\\Desktop\\readme.pdf");
        final String toFile = "C:\\Users\\zhbcm\\Desktop\\readme2.pdf";
        mergePdfFiles(list, toFile);
    }
    /**
     * 合并多个 PDF 文件为一个
     * @param list 要合并的 PDF 文件绝对路径列表
     * @param toFile 合并后的 PDF 文件绝对路径
     * @throws IOException
     */
    public static void mergePdfFiles(List<String> list, String toFile) throws IOException {
        final PdfDocument toPdf = new PdfDocument(new PdfWriter(toFile));
        PdfMerger merger = new PdfMerger(toPdf);
        for (String file : list) {
            final PdfDocument pdfDocument = new PdfDocument(new PdfReader(file));
            merger.merge(pdfDocument, 1, pdfDocument.getNumberOfPages());
            pdfDocument.close();
        }
        merger.close();
        toPdf.close();
    }
}
